

#include "Texture.h"

#include <cmath>



Texture::Texture()
{}

Texture::Texture(const char* filename)
{
	openFile(filename);
}

COLORREF Texture::getPixel(Float3D u,Float3D v)const
{
	//assert( is_smaller_or_equal(u,1.0f) );
	//assert( is_greater_or_equal(u,0.0f) );
	//assert( is_smaller_or_equal(v,1.0f) );
	//assert( is_greater_or_equal(v,0.0f) );

	return _nearest_sampling( u,v);
}


COLORREF Texture::_nearest_sampling(Float3D u,Float3D v)const
{
	return WinPic::getPixel( round( u * (getWidth()-1) ) , round(v * (getHeight()-1) ) );
}

COLORREF Texture::_bilinear_sampling(Float3D u,Float3D v)const
{
	Float3D x = u * getWidth();
	Float3D y = v * getHeight();

	Float3D x_low = (Float3D)(int)x;
	Float3D x_high = (Float3D)(((int)x)+1);
	Float3D y_low = (Float3D)(int)y;
	Float3D y_high = (Float3D)(((int)y)+1);


	COLORREF rgb_ll = WinPic::getPixel(round(x_low),round(y_low)); 
	COLORREF rgb_hl =  WinPic::getPixel(round(x_high),round(y_low)); 
	COLORREF rgb_lh =  WinPic::getPixel(round(x_low),round(y_high)); 
	COLORREF rgb_hh =  WinPic::getPixel(round(x_high),round(y_high)); 

	Point3D pt_ll = build_point_3D(GetRValue(rgb_ll),GetGValue(rgb_ll),GetBValue(rgb_ll));
	Point3D pt_hl = build_point_3D(GetRValue(rgb_hl),GetGValue(rgb_hl),GetBValue(rgb_hl));
	Point3D pt_lh = build_point_3D(GetRValue(rgb_lh),GetGValue(rgb_lh),GetBValue(rgb_lh));
	Point3D pt_hh = build_point_3D(GetRValue(rgb_hh),GetGValue(rgb_hh),GetBValue(rgb_hh));

	Point3D pt_color = ( pt_ll * fabs(x-x_high) + pt_hl * fabs(x-x_low) ) * fabs(y-y_high) + (pt_lh * fabs(x-x_high) + pt_hh * fabs(x-x_low))* fabs(y-y_low);


	//Float3D size_ll = abs((x-x_low)*(y-y_low))//build_point_2D(x-x_low,y-y_low).Length();
	//Float3D size_hl = //build_point_2D(x-x_high,y-y_low).Length();
	//Float3D size_lh =// build_point_2D(x-x_low,y-y_high).Length();
	//Float3D size_hh = //build_point_2D(x-x_high,y-y_high).Length();

	//Float3D total = length_ll + length_hl + length_lh + length_hh;
	//
	//Point3D pt =
	//   (build_point_3D(GetRValue(rgb_ll),GetGValue(rgb_ll),GetBValue(rgb_ll)) * length_ll
	//+	build_point_3D(GetRValue(rgb_hl),GetGValue(rgb_hl),GetBValue(rgb_hl)) * length_hl
	//+	build_point_3D(GetRValue(rgb_lh),GetGValue(rgb_lh),GetBValue(rgb_lh)) * length_lh
	//+	build_point_3D(GetRValue(rgb_hh),GetGValue(rgb_hh),GetBValue(rgb_hh)) * length_hh ) / total;



	return RGB(round(pt_color.x()),round(pt_color.y()),round(pt_color.z()));
}